/**
*  $Id: 2015年1月28日
*  quicklz1.5 functions for Lua
*  @author  lmess
*/

#include <stdlib.h>
#include <string.h>

#include <lua.h>
#include <lauxlib.h>

#include "quicklz.h"
#include "compat-5.2.h"



static int lcompress (lua_State *L) {
	size_t tarsize;
	const char *file_data = luaL_checklstring(L, 1, &tarsize);
	size_t c;
	char *compressed;
	qlz_state_compress *state_compress = (qlz_state_compress *)malloc(sizeof(qlz_state_compress));
	memset(state_compress, 0, sizeof(qlz_state_compress)); 
	compressed = (char *)lua_newuserdata(L, tarsize + 400);//compressed = (char*) malloc(tarsize + 400); 
	c = qlz_compress(file_data, compressed, tarsize, state_compress);
	lua_pushlstring(L, compressed, c);
	lua_pushinteger(L, c);
	free(state_compress);
	return 2;
}

static int ldecompress (lua_State *L) {
	size_t tarsize;
	const char *file_data =luaL_checklstring(L, 1, &tarsize);
	char *decompressed;
	size_t d,t;
	qlz_state_decompress *state_decompress = (qlz_state_decompress *)malloc(sizeof(qlz_state_decompress));
	memset(state_decompress, 0, sizeof(qlz_state_decompress)); 
	t = qlz_size_decompressed(file_data);
	decompressed = (char *)lua_newuserdata(L, t);//decompressed = (char*) malloc(t);
	d = qlz_decompress(file_data, decompressed, state_decompress);
	lua_pushlstring(L, decompressed, d);
	free(state_decompress);
	return 1;
}


/*
** Assumes the table is on top of the stack.
*/
static void set_info (lua_State *L) {
	lua_pushliteral (L, "_COPYRIGHT");
	lua_pushliteral (L, "Copyright (C) 2014-2024");
	lua_settable (L, -3);
	lua_pushliteral (L, "_DESCRIPTION");
	lua_pushliteral (L, "Basic quicklz facilities");
	lua_settable (L, -3);
	lua_pushliteral (L, "_VERSION");
	lua_pushliteral (L, "quicklz 1.5");
	lua_settable (L, -3);
}


static struct luaL_Reg qlzlib[] = {
  {"compress", lcompress},
  {"decompress", ldecompress},
  {NULL, NULL}
};


int luaopen_quicklz_core (lua_State *L) {
  lua_newtable(L);
  luaL_setfuncs(L, qlzlib, 0);
  set_info (L);
  return 1;
}